﻿using LibBinary.DataSource;
using LibBinary.FileData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LibBinary.FileDeclaration.Binary
{
    //TODO support unordered structured data
    //TODO support object data
    public class StructuredDeclaration : IFileDeclaration
    {
        private readonly IFileDeclaration[] children;

        public StructuredDeclaration(IFileDeclaration[] children)
        {
            this.children = children;
        }

        public AbstractFileData Read(BinaryFileSource src, AbstractFileData parentNode)
        {
            var ret = new StructuredData(parentNode);
            AbstractFileData[] list = new AbstractFileData[children.Length];
            ret.Data = list;
            for (int i = 0; i < list.Length; ++i)
            {
                list[i] = children[i].Read(src, ret);
            }
            return ret;
        }

        public void Write(BinaryFileSource src, AbstractFileData data)
        {
            var cdata = data.As<StructuredData>();
            if (cdata == null)
            {
                throw new WritingFormatException("Wrong data type.");
            }
            if (cdata.Data.Length != children.Length)
            {
                throw new WritingFormatException("Structured data size mismatch.");
            }
            for (int i = 0; i < cdata.Data.Length; ++i)
            {
                children[i].Write(src, cdata.Data[i]);
            }
        }
    }
}
